<template>
  <div class="fk-box">
    <header>
      <el-button type="primary" @click="handleStart">start</el-button>
      score:{{ elsfk?.score }}
    </header>
    <div class="leafer-box">
      <canvas id="leafer-view"></canvas>
    </div>
    <footer>footer</footer>
  </div>
</template>

<script lang="ts" setup>
import Elsfk from "./index.ts";

const elsfk = ref<InstanceType<typeof Elsfk> | null>(null);
const pauseFlag = ref(false);

const init = () => {
  elsfk.value = new Elsfk("leafer-view");
};
const initKeyboard = (e: KeyboardEvent) => {
  if (!elsfk.value?.gameFlag) return; // 游戏未开始 不能操作
  if (e.code === "Space") {
    e.preventDefault();
    pauseFlag.value ? elsfk.value?.play() : elsfk.value?.pause();
    pauseFlag.value = !pauseFlag.value;
  }
  if (pauseFlag.value) return; // 暂停时不能变换
  if (e.code === "ArrowUp") {
    e.preventDefault();
    elsfk.value?.onRotate();
  } else if (e.code === "ArrowDown") {
    e.preventDefault();
    elsfk.value?.onDown();
  } else if (e.code === "ArrowLeft") {
    e.preventDefault();
    elsfk.value?.onLeft();
  } else if (e.code === "ArrowRight") {
    e.preventDefault();
    elsfk.value?.onRight();
  }
};
const handleStart = () => {
  elsfk.value!.start();
};

onMounted(() => {
  init();
  document.addEventListener("keydown", initKeyboard);
});
onUnmounted(() => {
  document.removeEventListener("keydown", initKeyboard);
});
</script>

<style scoped lang="scss">
.fk-box {
  display: flex;
  flex-direction: column;
  height: 100vh;
  header,
  footer {
    height: 40px;
    line-height: 40px;
  }
}
.leafer-box {
  flex: 1;
}
</style>
